<?php
namespace app\spider\service\content;
use QL\QueryList;
use QL\Ext\CurlMulti;
use QL\Ext\AbsoluteUrl;

class BtContentService extends AbstractBaseService
{
    /**
     *
     * @param QueryList $ql
     * @param CurlMulti $curl
     * @param $r
     * @param array $args
     * @return mixed|void
     */
    public function process(QueryList $ql, CurlMulti $curl, $r, $args = []){
        echo $r['info']['url'],"\n";
        preg_match('/^(https?:\/\/)?[\d\w]{0,}\.?[\d\w]+\.\w+\/?/i', $r['info']['url'],$baseUrl);

        $baseUrl = trim($baseUrl[0],'/');
        $site_info = $this->params[$baseUrl];

        $ql->html($r['body']);
        $charset = strtoupper($site_info['charset']);
        if($charset != 'UTF-8'){
            $ql->encoding('UTF-8', $charset);
        }

        $content_reg = $site_info['content_reg'];
        $content = $ql->rules([
            'content' => $content_reg['content']
        ])->query()->getData()->all();
        $content = empty($content) ? '' : $content[0]['content'];

        $url_info = parse_url($r['info']['url']);
        $url_info['path'] = explode('/', $url_info['path']);
        $path = array_pop($url_info['path']);
        preg_match("/\d+/", $path, $id);
        $id = intval(array_pop($id));
        if (!$id) {
            return ;
        }

        $args['content'] = $content;
        $args['url'] = $r['info']['url'];
        $curl->addTasks(["http://www.btbtdy.me/vidlist/{$id}.html"], function ($r) use ($args, $content, $ql, $curl){
            $this->processSources($ql, $curl, $r, $args);
        });


    }


    public function processSources(QueryList $ql, CurlMulti $curl, $r, $args) {
        echo $r['info']['url'],"\n";

        $url_info = parse_url($r['info']['url']);
        $baseUrl = $url_info['scheme'] . '://' . $url_info['host'];
        $site_info = $this->params[$baseUrl];

        $ql->html($r['body']);
        $charset = strtoupper($site_info['charset']);
        if($charset != 'UTF-8'){
            $ql->encoding('UTF-8', $charset);
        }

        $content_reg = $site_info['content_reg'];
        $sources = $ql->rules([
            'source'     => $content_reg['link'],
            'source_txt' => $content_reg['link_text'],
        ])->query()->getData()->all();
        foreach($sources as $key=>$value){
            if($source = $this->checkSourceLink($value['source'], $baseUrl, $r['info']['url'])) {
                $sources[$key] = $source;
                $sources[$key]['title'] = isset($value['source_txt']) ? $value['source_txt'] : '';
            }else{
                unset($sources[$key]);
            }
        }

        $this->saveData($sources, $args['url'], $args['content'], $site_info['id'], $args['title']);
    }
}
